﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.Management
{
    public class EditManagementModel
    {
        public int ManagementId { get; set; }

        [DisplayName("Nombre de Jefatura/Gerencia")]
        [Required(ErrorMessage = "El nombre de la Jefatura/Gerencia es requerida")]
        [StringLength(50, ErrorMessage = "El nombre debe ser máximo de 50 caracteres")]
        [RegularExpression(@"^[a-zA-Z0-9 \(\)ñÑ\-.,áéíóúÁÉÍÓÚ]+$", ErrorMessage = "El nombre debe ser solo letras o números")]
        public string Name { get; set; }

        [DisplayName("Jefatura/Gerencia Padre")]
        [Required(ErrorMessage = "Una jefatura/gerencia es necesaria")]
        public int Parent { get; set; }

        [DisplayName("Responsable")]
        [Required(ErrorMessage = "El usuario responsable es requerido")]
        public int Responsible { get; set; }

        public IEnumerable<SelectListItem> Managements
        {
            get
            {
                return managements;
            }
        }

        public IEnumerable<SelectListItem> Users
        {
            get
            {
                return users;
            }
        }

        private List<SelectListItem> managements;
        private List<SelectListItem> users;
        riskanalysisEntities entities;

        public EditManagementModel()
        {
            entities = new riskanalysisEntities();
            managements = new List<SelectListItem>();
            users = new List<SelectListItem>();            
        }

        public EditManagementModel(int managementId)
            : this()
        {
            FillLists(managementId);
            FillManagementById(managementId);
        }

        private void FillManagementById(int id)
        {
            management theManagement = GetManagementById(id);
            
            ManagementId = theManagement.managementId;
            Name = theManagement.name;
            Parent = theManagement.parentManagement != null ? theManagement.parentManagement.Value : 0;
            Responsible = theManagement.responsible;
        }

        private management GetManagementById(int id)
        {
            var query = from m in entities.managements
                        where m.managementId == id
                        select m;

            management theManagement = query.FirstOrDefault();

            if (theManagement == null)
                throw new EditManagementException("La jefatura/gerencia que usted busca no existe");
            return theManagement;
        }

        private void FillLists(int id)
        {
            int privilege = Convert.ToInt32(Privileges.AreaSecurity);
            var queryUser = from u in entities.users
                            where u.privilege <= privilege && u.enabled
                            select u;

            foreach (user item in queryUser)
            {
                users.Add(new SelectListItem
                    {
                        Text = item.firstName + " " + item.lastName + " " + item.secondLastName,
                        Value = item.CI.ToString()
                    });
            }

            var queryManagements = from m in entities.managements
                                   where m.managementId != id && m.enabled
                                   select m;

            foreach (management item in queryManagements)
            {
                managements.Add(new SelectListItem
                {
                    Text = item.name,
                    Value = item.managementId.ToString()
                });
            }
        }

        public void Save()
        {
            management theManagement = GetManagementById(ManagementId);

            theManagement.name = Name;
            theManagement.parentManagement = Parent != 0 ? new int?(Parent) : null;
            theManagement.responsible = Responsible;
            entities.SaveChanges();
        }
    }
}